package com.search.poi.builder;

import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.search.poi.BaiduDistrictConstant;
import com.search.poi.domain.BaiduMeta;
import com.search.poi.domain.LbsDistrictMeta;
import com.search.poi.domain.LbsMeta;
import com.search.poi.domain.User;
import net.dreamlu.mica.http.HttpRequest;
import net.dreamlu.mica.http.ResponseSpec;

public class POIBuilder {
	
	private List<User> list;
	
	private POIBuilder () {}
	
	public static POIBuilder create() {
		POIBuilder builder = new POIBuilder();
		builder.list = new ArrayList<User>();
		return builder;
	}
	public List<User> buidler(){
		return list;
	}
	/**
	 * 
	 * @Description: 高德
	 * @author zhengchuanqing
	 * @date 2020年4月1日 下午4:40:12
	 * @return POIBuilder
	 * @throws
	 */
	public POIBuilder lbs(String keywords, String city, int offset, int page) {
		StringBuilder builder = new StringBuilder();
		//企业30万配额
		builder.append("key=").append("24e8028208ff52e01738e1327aefe5d83");
		builder.append("&keywords=").append(keywords);
		builder.append("&city=").append(city);
		builder.append("&offset=").append(offset);
		builder.append("&page=").append(page);
		String url = "https://restapi.amap.com/v3/place/text?" + builder.toString();
		//System.out.println(url);
		String text = HttpRequest.get(url).execute().onFailed((request, e) -> {
			e.printStackTrace();
		}).onResponse(ResponseSpec::asString);
		
		if (text != null && !"".equals(text.trim()) ) {
			JSONObject jsonObject = JSON.parseObject(text);
			String cities = jsonObject.getJSONObject("suggestion").getString("cities");
			List<LbsDistrictMeta> districtMetas = null;
			if (cities != null && !"".equals(cities.trim())) {
				districtMetas = JSON.parseArray(cities, LbsDistrictMeta.class);
			}
			if (districtMetas == null || districtMetas.isEmpty()) {
				//单个城市搜索
				lbsParse(keywords, city, offset, page, text);
			} else {
				//全国搜索
				for (LbsDistrictMeta districtMeta : districtMetas) {
					page = 1;
					System.out.println(districtMeta.getAdcode());
					lbs(keywords, districtMeta.getAdcode(), offset, page);
				}
			}
		
		}
		return this;
	}
	/**
	 * 
	 * @Description: 高德数据解析
	 * @author zhengchuanqing
	 * @date 2020年4月1日 下午4:47:27
	 * @return void
	 * @throws
	 */
	private void lbsParse(String keywords, String city, int offset, int page, String text) {
		JSONObject jsonObject = JSON.parseObject(text);
		int count = jsonObject.getInteger("count");
		String poisText = jsonObject.getString("pois");
		if (poisText != null && !"".equals(poisText.trim())) {
			List<LbsMeta> users = JSON.parseArray(poisText, LbsMeta.class);
			for (LbsMeta meta : users) {
				if (("".equals(meta.getTel()) || meta.getTel() == null)
						&& ("".equals(meta.getAddress()) || meta.getAddress() == null)) {
					continue;
				}
				User user = new User();
				user.setAddress(meta.getAddress());
				user.setAdname(meta.getAdname());
				user.setCityname(meta.getCityname());
				user.setName(meta.getName());
				user.setPname(meta.getPname());
				user.setTel(meta.getTel());
				user.setType(meta.getType());
				list.add(user);
			}
		}
		int result = offset * page;
		if (result < count) {
			page += 1;
			lbs(keywords, city, offset, page);
		}
	}
	
	
	
	public POIBuilder baidu(String keywords, String city, int offset, int page, boolean loadAll) {

		if (!loadAll) {
			//false 则表示搜索单个地区的数据
			baiduRequest(keywords, city, offset, page);
		} else {
			//搜索全国数据
			String[] districts = BaiduDistrictConstant.district.split(",");
			for (int i = 0; i < districts.length; i++) {
				System.out.println("i=" + i + "  ; " + districts[i]);
				baiduRequest(keywords, districts[i], offset, page);
			}
		}
		
		return this;
	}
	/**
	 * 
	 * @Description: 百度POI请求
	 * @author zhengchuanqing
	 * @date 2020年4月1日 下午5:12:26
	 * @return void
	 * @throws
	 */
	private void baiduRequest(String keywords, String city, int offset, int page) {
		StringBuilder builder = new StringBuilder();
		builder.append("ak=").append("YBIAaQKYefk6jl2wyH76U1luKhFtnHzn0");
		builder.append("&query=").append(keywords);
		//	检索分类偏好，与q组合进行检索，多个分类以","分隔（POI分类），如果需要严格按分类检索，请通过query参数设置------------>可选
		//builder.append("&tag=").append(keywords);
		builder.append("&region=").append(city);
		builder.append("&output=json");
		//单次召回POI数量，默认为10条记录，最大返回20条。多关键字检索时，返回的记录数为关键字个数*page_size。
		builder.append("&page_size=").append(offset);
		//分页页码，默认为0,0代表第一页，1代表第二页，以此类推。常与page_size搭配使用。
		builder.append("&page_num=").append(page);
		String url = "http://api.map.baidu.com/place/v2/search?" + builder.toString();
		
		String text = HttpRequest.get(url).execute().onFailed((request, e) -> {
			e.printStackTrace();
		}).onResponse(ResponseSpec::asString);
		
		if (text != null && !"".equals(text.trim()) ) {
			JSONObject jsonObject = JSON.parseObject(text);
			int total = jsonObject.getInteger("total");
			String resultsText = jsonObject.getString("results");
			if (resultsText != null && !"".equals(resultsText.trim())) {
				List<BaiduMeta> users = JSON.parseArray(resultsText, BaiduMeta.class);
				for (BaiduMeta meta : users) {
					if (("".equals(meta.getTelephone()) || meta.getTelephone() == null)
							&& ("".equals(meta.getAddress()) || meta.getAddress() == null)) {
						continue;
					}
					User user = new User();
					user.setAddress(meta.getAddress());
					user.setAdname(meta.getArea());
					user.setCityname(meta.getCity());
					user.setName(meta.getName());
					user.setPname(meta.getProvince());
					user.setTel(meta.getTelephone());
					list.add(user);
				}
			}
			int result = offset * page;
			if (result < total) {
				page += 1;
				baiduRequest(keywords, city, offset, page);
			}
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}
	
}
